package com.changgou.seckill.task;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

//秒杀定时任务
@Component
public class SeckillGoodsPushTask {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //设置一个常量
    private static final String SECKILL_GOODS_KEY="seckill_goods_";

    //定时将秒杀商品存入redis,暂定为30秒一次，正常业务为每天凌晨触发
    @Scheduled(cron = "0/30 * * * * ?")
    public void loadSecKillGoodsToRedis(){
        //获取时间菜单
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {
            //每次用最好都重新new
            //开始
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //结束
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //把时间段转化为字符串
            String redisExtName = DateUtil.date2Str(dateMenu);

            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();

            //状态=1
            criteria.andEqualTo("status","1");
            //库存大于0
            criteria.andGreaterThan("stockCount",0);
            //开始时间大于等于当前时间段
            criteria.andGreaterThanOrEqualTo("startTime",simpleDateFormat
                    .format(dateMenu));
            //结束时间小于当前时间段+2小时
            criteria.andLessThan("endTime",simpleDateFormat1.
                    format(DateUtil.addDateHour(dateMenu,2)));
            //获取redis中的所有key
            Set keys = redisTemplate.boundHashOps(SECKILL_GOODS_KEY + redisExtName).keys();
            if (keys!=null&&keys.size()>0){
                //判断当前秒杀商品不再redis中
                criteria.andNotIn("id",keys);
            }
            //获取秒杀商品集合
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            //添加到缓存中
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(SECKILL_GOODS_KEY+redisExtName)
                        .put(seckillGood.getId(),seckillGood);
            }
        }

    }

}
